
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>

#include <libifconfig.h>

#include "qserver.h"

#ifdef __cplusplus

Lib_QServer::Lib_QServer(void)
{
}

Lib_QServer::~Lib_QServer(void)
{
}

void Lib_QServer::loop(int interval, void (*handle_call)(void *arg), void *arg)
{
	while(1)
	{
		m_epoll->wait(interval, Lib_QServer::socketHandle, this);

		if(NULL != handle_call)
		{
			handle_call(arg);
		}
	}
}

void Lib_QServer::socketHandleWork(int fd)
{
	
}

void Lib_QServer::socketHandle(void *arg, int fd)
{
	Lib_QServer *obj = (Lib_QServer *)arg;

	if(NULL != obj)
	{
		obj->socketHandleWork(fd);
	}
}

Lib_QServer *Lib_QServer::getObject(const char *name, unsigned short port)
{
	Lib_QServer *obj = NULL;

	char ipaddr[32] = {0};

	// TODO: 检查参数
	// TODO: 如果参数不合法，直接返回NULL到调用处
	if(NULL == name || 0 >= port)
	{
		goto out;
	}

	obj = new Lib_QServer();

	if(NULL == obj)
	{
		goto out;
	}

	obj->m_epoll = Lib_Epoll::getObject();

	if(0 > obj->m_epoll)
	{
		goto out1;
	}

	if(true != Lib_IfConfig::getInterfaceIpAddr(ipaddr, ipaddr, sizeof(ipaddr)))
	{
		goto out2;
	}

	obj->m_fd = Lib_IfConfig::listenOn(ipaddr, port);

	if(0 > obj->m_fd)
	{
		goto out2;
	}

	goto out;

out2:
	if(NULL != obj->m_epoll)
	{
		delete obj->m_epoll;
		obj->m_epoll = NULL;
	}
out1:
	if(NULL != obj)
	{
		delete obj;
		obj = NULL;
	}
out:
	return obj;
}

#endif
